package com.yuandian.management.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.entity.ConfSystem;
import com.yuandian.api.management.entity.ConfUnit;
import com.yuandian.bpm.admin.api.entity.SysUser;
import com.yuandian.bpm.admin.api.feign.RemoteUserService;
import com.yuandian.bpm.common.core.constant.SecurityConstants;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.mapper.ConfUnitMapper;
import com.yuandian.management.service.ConfSystemService;
import com.yuandian.management.service.ConfUnitService;
import com.yuandian.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 单位配置表-Service实现
 * @author zfsn
 * @date 2023-6-12
 */
@Service
public class ConfUnitServiceImpl extends ServiceImpl<ConfUnitMapper, ConfUnit>
		implements ConfUnitService {

	@Autowired
	private ConfUnitMapper confUnitMapper;

	@Autowired
	private RemoteUserService remoteUserService;

	@Autowired
	private ConfSystemService confSystemService;


	/**
	 * 分页查询
	 *
	 * @param confUnit 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfUnit> listPage(ConfUnit confUnit) {
		if (StringUtils.isNotBlank(confUnit.getUserName())){
			List<SysUser> data = remoteUserService.fuzzyQuery(confUnit.getUserName(), SecurityConstants.FROM_IN).getData();
			if (data.size() > 0) {
				confUnit.setUserIds(data.stream().map(SysUser::getUserId).collect(Collectors.toList()));
			}
		}
		Map<Long, String> data = remoteUserService.getAllUser(SecurityConstants.FROM_IN).getData();

		Page<ConfUnit> confUnitPage = confUnitMapper.listPage(new Page<>(confUnit.getPageNum(), confUnit.getPageSize()), confUnit);
		Map<Integer, String> systemMap = confSystemService.list().stream().collect(Collectors.toMap(ConfSystem::getId, ConfSystem::getName));
		for (ConfUnit unitPageRecord : confUnitPage.getRecords()) {
			unitPageRecord.setUserName(data.get(Long.valueOf(unitPageRecord.getUserId())));
			unitPageRecord.setSystemName(systemMap.get(Integer.valueOf(unitPageRecord.getSystemId())));
		}
		return confUnitPage;
	}



	/**
	 * 新增数据
	 *
	 * @param confUnit
	 * @return 通用返回对象
	 * @panfUnit 实例对象
	 */
	@Override
	public R<String> saveData(ConfUnit confUnit) {
		if (checkNameDuplicates(confUnit)) {
			return R.failed("单位名称存在重复");
		}
		List<ConfUnit> confUnits = new ArrayList<>();
		long snowflakeNextId = IdUtil.getSnowflakeNextId();
		for (Integer systemId : confUnit.getSystemIds()) {
			for (Long userId : confUnit.getUserIds()) {
				ConfUnit unit = new ConfUnit();
				unit.setName(confUnit.getName());
				unit.setSystemId(systemId);
				unit.setUserId(String.valueOf(userId));
				unit.setCode(String.valueOf(snowflakeNextId));
				String userName = SecurityUtils.getUser().getName();
				unit.setCreateBy(userName);
				unit.setUpdateBy(userName);
				LocalDateTime now = LocalDateTime.now();
				unit.setCreateTime(now);
				unit.setUpdateTime(now);
				confUnits.add(unit);
			}
		}
		super.saveBatch(confUnits);
		return R.ok("保存数据成功");
	}

	/**
	 * 通过主键更新数据
	 *
	 * @param confUnit 实例对象
	 * @return 通用返回对象
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R<String> updateData(ConfUnit confUnit) {
		if (checkNameDuplicates(confUnit)) {
			return R.failed("单位名称存在重复");
		}
		LambdaUpdateWrapper<ConfUnit> updateWrapper = Wrappers.lambdaUpdate();
		updateWrapper.eq(ConfUnit::getCode, confUnit.getCode());
		super.remove(updateWrapper);
		List<ConfUnit> confUnits = new ArrayList<>();
		long snowflakeNextId = IdUtil.getSnowflakeNextId();
		for (Integer systemId : confUnit.getSystemIds()) {
			for (Long userId : confUnit.getUserIds()) {
				ConfUnit unit = new ConfUnit();
				unit.setName(confUnit.getName());
				unit.setSystemId(systemId);
				unit.setUserId(String.valueOf(userId));
				unit.setCode(String.valueOf(snowflakeNextId));
				String userName = SecurityUtils.getUser().getName();
				unit.setCreateBy(userName);
				unit.setUpdateBy(userName);
				LocalDateTime now = LocalDateTime.now();
				unit.setCreateTime(now);
				unit.setUpdateTime(now);
				confUnits.add(unit);
			}
		}
		super.saveBatch(confUnits);
		return R.ok("修改数据成功");
	}


	/**
	 * 判断单位名称是否重复
	 * @param confUnit
	 */
	private boolean checkNameDuplicates(ConfUnit confUnit) {
		LambdaQueryWrapper<ConfUnit> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(ConfUnit::getName, confUnit.getName());
		if (StringUtils.isNotBlank(confUnit.getCode())){
			queryWrapper.ne(ConfUnit::getCode, confUnit.getCode());
		}
		return super.list(queryWrapper).size() > 0;
	}
}